<template>
  <div class="frame-page flex flex-column">
    <vxe-toolbar>
      <template #buttons>
        <div class="h-input-group">
          <span class="h-input-addon">单据日期</span>
          <DateRangePicker v-model="dateRange"></DateRangePicker>
        </div>
        <Search v-model.trim="params.filter" search-button-theme="h-btn-default"
                show-search-button class="w-360px ml-8px"
                placeholder="请输入订单号/客户名称" @search="doSearch">
          <i class="h-icon-search"/>
        </Search>
      </template>
      <template #tools>
        <!--        <Button @click="toVoucher()" color="primary">生成凭证</Button>-->
      </template>
    </vxe-toolbar>
    <div class="flex1">
      <vxe-table row-id="id"
                 ref="table"
                 height="auto"
                 :data="dataList"
                 highlight-hover-row
                 show-overflow
                 show-footer
                 :footer-method="footerMethod"
                 :row-config="{height: 48}"
                 :column-config="{resizable: true}"
                 :sort-config="{remote:true}"
                 @sort-change="sortChangeEvent"
                 :loading="loading">
        <vxe-column type="checkbox" width="40" align="center"/>
        <vxe-column type="seq" width="50" title="序号"/>
        <vxe-column title="订单单号" field="code" min-width="200">
          <template  #default="{row}">
            <span @click="toOrder">
              {{row.code}}
            </span>
          </template>
        </vxe-column>
        <vxe-column title="订单类型" field="orderType" width="160"/>
        <vxe-column title="订单金额" field="discountedAmount" width="160"/>
        <vxe-column title="单据日期" field="billDate" align="center" width="160"/>
        <vxe-column title="凭证字号"  align="center" width="160">
          <template #default="{row}">
            <span v-if="row.voucherWord">
              {{ row.voucherWord }}-{{ row.voucherCode }}
            </span>
          </template>
        </vxe-column>
        <vxe-column title="凭证时间" field="voucherDate" align="center" width="160"/>
        <vxe-column title="操作" align="center" width="200">
          <template #default="{row}">
            <span class="primary-color  text-hover ml-10px" v-if="row.voucherWord"
                  @click="showView(row)">查看凭证</span>
            <span class="primary-color  text-hover ml-10px" v-else
                  @click="toVoucher(row.id,row.purchaserOrderState)">生成凭证</span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div class="flex justify-between items-center pt-5px">
      <div>
        <!--        <vxe-button @click="batchState">批量审核</vxe-button>-->
        <!--        <vxe-button @click="batchPay">批量付款</vxe-button>-->
      </div>
      <vxe-pager perfect @page-change="loadList(false)"
                 v-model:current-page="pagination.page"
                 v-model:page-size="pagination.pageSize"
                 :total="pagination.total"
                 :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']">
        <template #left>
          <!--          <span class="mr-12px text-16px">总金额：{{ amountTotal }}元</span>-->
          <vxe-button @click="loadList(false)" type="text" size="mini" icon="fa fa-refresh"
                      :loading="loading"></vxe-button>
        </template>
      </vxe-pager>
    </div>
  </div>
</template>
<script>
import {confirm, message} from "heyui.ext";
import manba from "manba";
import OrderVoucher from "@js/api/RelationVoucher";
import RelationVoucher from "@js/api/RelationVoucher";
import VoucherForm from "@components/group/setting/VoucherForm.vue";
import {layer} from "@layui/layer-vue";
import {h} from "vue";

const startTime = manba().startOf(manba.MONTH).format("YYYY-MM-dd");
const endTime = manba().endOf(manba.DAY).format("YYYY-MM-dd");

export default {
  name: "RelationOrderVoucher",
  data() {
    return {
      dataList: [],
      loading: false,
      amountTotal: 0,
      totalParams: {},
      pagination: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      params: {
        filter: null,
        state: '已审核',
        sortCol: null,
        sort: null,
        orderType: '采购订单',
      },
      dateRange: {
        start: manba(startTime).format("YYYY-MM-dd"),
        end: manba(endTime).format("YYYY-MM-dd")
      },
    }
  },
  computed: {
    queryParams() {
      return Object.assign(this.params, {
        page: this.pagination.page,
        pageSize: this.pagination.pageSize,
        start: this.dateRange.start,
        end: this.dateRange.end,
      })
    },
    downParams() {
      return Object.assign({
        filter: this.params.filter,
        state: this.params.state,
        orderType: this.params.orderType,
        start: this.dateRange.start,
        end: this.dateRange.end,
      })
    }
  },
  methods: {
    sortChangeEvent({field, order}) {
      this.params.sortCol = field;
      this.params.sort = order;
      this.loadList(false);
    },
    footerMethod({columns, data}) {
      let sums = [];
      columns.forEach((column) => {
        if (column.property && ['discountedAmount'].includes(column.property)) {
          let total = 0;
          data.forEach((row) => {
            let rd = row[column.property];
            if (rd) {
              total += Number(rd || 0);
            }
          });
          sums.push(total.toFixed(2));
        }
      })
      return [["", "", "", "", "", ""].concat(sums)];
    },
    showView(row, params = {}){
      let layerId = layer.drawer({
        title: false,
        shadeClose: false,
        zIndex: 1000,
        area: ['1200px', '100vh'],
        content: h(VoucherForm, Object.assign({
          voucherId:  row.id,
          voucherCode: row.voucherCode,
          voucherWord: row.voucherWord,
          voucherDate: row.voucherDate,
          onSuccess: () => {
            layer.close(layerId);
            this.loadList();
          },
          onClose: () => {
            layer.close(layerId);
          }
        },params)),
        onClose: () => {
          this.loadList();
        }
      });
    },
    toVoucher(orderId = null, state) {
      OrderVoucher.toVoucher(orderId).then(({data, success}) => {
      if(success){
        message("保存成功~");
        this.doSearch()
      }
      })
    },
    doSearch() {
      this.pagination.page = 1;
      this.loadList();
    },
    loadList() {
      this.loading = true;
      RelationVoucher.list(this.queryParams).then(({data: {results, total}}) => {
        this.dataList = results || [];
        this.pagination.total = total;
      }).finally(() => this.loading = false);
    },
  },
  created() {
    this.loadList();
  }
}
</script>
